{include file="$header" /}
<div class="mk-app-warp">
    <mk-table-header
        :add-url="addUrl"
        :del-url="delUrl"
        :rows="rows"
        @del="del()"
        @add="openDrawer()"
        @search="getData()">
    </mk-table-header>
    <el-table
        class="sort-table"
        row-key="name"
        ref="dragTable" 
        highlight-current-row
        :data="table"
        v-loading="loading"
        @selection-change="checkSelected">
        <el-table-column type="selection" width="55" :selectable="checkDisabled"></el-table-column>
        <el-table-column prop="cover" label="语言封面">
            <template slot-scope="scope">
                <el-image :src="domain + scope.row.cover" style="width: 48px; height: 32px">
                    <div slot="error" class="image-slot">
                        <img class="error-image" :src="static + '/images/error.png'"/>
                    </div>
                </el-image>
            </template>
        </el-table-column>
        <el-table-column prop="title" label="语言名称"></el-table-column>
        <el-table-column prop="name" label="语言缩写"></el-table-column>
        <el-table-column prop="default" label="默认语言">
            <template slot-scope="scope">
                <el-button 
                    type="primary" 
                    size="mini" 
                    v-if="scope.row.default === 0" 
                    @click="reDefault(scope.row)"
                    :disabled="editAuthority === false || scope.row.status === 0"
                    plain>
                    设为默认
                </el-button>
                <el-button plain v-else size="mini">默认</el-button>
            </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100px">
            <template slot-scope="scope">
                <el-switch
                    v-model="scope.row.status"
                    active-color="#13ce66"
                    inactive-color="#ff4949"
                    :active-value="1"
                    :inactive-value="0"
                    @change="fieldEdit(scope.row, 'status')"
                    :disabled="editAuthority === false || scope.row.default === 1">
                </el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
                <mk-table-public
                    :edit-url="editUrl"
                    :del-url="delUrl"
                    @edit="openDrawer(scope.$index)"
                    @del="del(scope.$index)">
                </mk-table-public>
            </template>
        </el-table-column>
    </el-table>
</div>
{include file="lang/drawer" /}
{include file="$component" /}
<script>
    new Vue({
        el: '#app',
        data() {
            var validateRepeatName = (rule, value, callback) => {
                if (this.drawerIndex === '') {
                    let isExist = common.arrayIndex(this.table, value, 'name');
                    if(isExist !== -1) {
                        callback(new Error('列表中已存在此语言！'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            }
            return {
                rows: [],
                table: [],
                url: "lang/index",
                addUrl: "lang/update",
                delUrl: "lang/update",
                editUrl: "lang/update",
                loading: false,
                drawer: false,
                drawerData: {},
                drawerForm: {
                    cover: "",
                    title: "",
                    name: "",
                    default: 0,
                    status: 1,
                    sort: 0,
                    parameter: [],
                },
                drawerRules: {
                    cover: [
                        { required: true, message: '请选择语言封面', trigger: 'blur' },
                    ],
                    title: [
                        { required: true, message: '请输入语言名称', trigger: 'blur' },
                        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
                    ],
                    name: [
                        { required: true, message: '请输入语言缩写', trigger: 'blur' },
                        { pattern: /^[A-Za-z0-9_\-]+$/ig, message: '只能为字母和数字，下划线_及破折号-', trigger: 'blur' },
                        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' },
                        { validator: validateRepeatName, trigger: 'blur' }
                    ],
                },
                drawerIndex: "",
                drawerLoading: false,
            }
        },
        mounted () {
            this.setSort();
        },
        created () {
            this.getData();
        },
        computed: {
            editAuthority() {
                return authorityPath.indexOf(this.editUrl) !== -1;
            },
        },
        methods: {
            /**
             * 获取数据
             */
            getData() {
                let self     = this;
                request.post(self.url, {}, function(res) {
                    self.table     = res.data;
                    self.changeLangs();
                    self.drawerForm.sort = typeof res.data[0] === 'undefined' ? 1 : res.data[0]['sort'] + 1;
                });
            },
            /**
             * 打开抽屉
             * @param  {Object} row 当前行
             */
            openDrawer(index = "") {
                let self = this;
                self.drawerData  = index === "" ? JSON.parse(JSON.stringify(self.drawerForm)) : JSON.parse(JSON.stringify(self.table[index]));
                this.drawerIndex = index;
                self.drawer = true;
            },
            /**
             * 保存内容
             */
            saveDrawer() {
                let self = this;
                self.$refs.drawerData.validate((valid) => {
                    if (valid) {
                        self.drawerLoading = true;
                        if (self.drawerData.default === 1) this.initDefault();
                        if (this.drawerIndex === "") {
                            self.table.push(self.drawerData);
                        } else {
                            self.table[this.drawerIndex] = self.drawerData;
                        }
                        request.post(self.editUrl, {value: self.table}, function(res){
                            self.drawerLoading = false;
                            if (res.status === 'success') {
                                self.getData();
                                self.drawer = false;
                            } else {
                                self.$message({ showClose: true, message: res.message, type: res.status});
                            }
                        });
                    } else {
                        return false;
                    }
                });
            },
            // 初始化默认值
            initDefault() {
                this.table.forEach(function(item, index) {
                    item.default = 0;
                });
            },
            /**
             * 单字段修改
             * @param  {Object} row 当前行
             */
            reDefault(row) {
                this.initDefault();
                row.default = 1;
                this.fieldEdit(row, 'default');
            },
            fieldEdit(row, field) {
                let self = this;
                request.post(self.editUrl, {value: self.table}, function(res) {
                    if (res.status != 'success') {
                        self.$message({ showClose: true, message: res.message, type: res.status});
                    }
                    self.getData();
                });
            },
            /**
             * 行删除、批量删除
             * @param  {Object} row 当前行
             */
            del(index = "") {
                let self = this;
                self.$confirm('确定删除吗？', '', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(index === ""){
                        self.rows.forEach(function (item, index) {
                            self.table.forEach(function (table, keys) {
                                if(table.name === item.name) {
                                    self.table.splice(keys, 1);
                                }
                            })
                        })
                    } else {
                        if (self.table[index]['default'] === 0) {
                            self.table.splice(index, 1);
                        } else {
                            self.$message({ showClose: true, message: '默认语言不能删除!', type: 'error'});
                            return;
                        }
                    }
                    request.post(self.delUrl, {value: self.table}, function(res){
                        self.$message({ showClose: true, message: res.message, type: res.status});
                        self.getData();
                    });
                }).catch(() => {});
            },
            /**
             * 选中行
             * @param  {Object} rows 多行数
             */
            checkSelected(rows) {
                this.rows = rows;
            },
            /**
             * 行不可选中
             * @param  {Object} row   [description]
             */
            checkDisabled(row) {
                return row.default === 1 ? false : true;
            },
            /**
             * 拖动排序
             */
            setSort(){
                let self = this;
                let el   = self.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
                self.sortable = Sortable.create(el,{
                    animation: 300,
                    forceFallback: true,
                    delay: 20,
                    onEnd: evt => {
                        if (evt.newIndex !== evt.oldIndex) {
                            let targetRow = self.table.splice(evt.oldIndex, 1)[0];
                            self.table.splice(evt.newIndex, 0, targetRow);
                            self.table.forEach(function (item, index) {
                                item.sort = self.table.length - index;
                                self.$set(self.table, index, item);
                            })
                            request.post(self.editUrl, {value: self.table}, function(res){
                                self.getData();
                            });
                        }
                    }
                })
            },
            /**
             * 动态改变父级的语言列表
             * @param  {Object} value 搜索内容
             */
            changeLangs() {
                var langAllow = [];
                this.table.forEach(function(item, index) {
                    if (item['status'] === 1) langAllow.push(item);
                })
                parent.parentVm.langAllow = langAllow;
            },
        },
        watch: {
            drawer(v) {
                if(! v){
                    // 重置表单
                    this.$refs.drawerData.resetFields();
                }
            },
        }
    })
</script>
{include file="$footer" /}